package com.fmi.timedealer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.fmi.timedealer.achievement.AchievementsActivity;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;
import com.fmi.timedealer.notifications.PlansNotificationManager;
import com.fmi.timedealer.track.TrackLog;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class RunningActivity extends ListActivity {

	private IDataManager dbManager = null;
	private ArrayList<TrackLog> activities = new ArrayList<TrackLog>();
	private HashMap<Long, ActivityItem> activitiesMap = new HashMap<Long, ActivityItem>();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.running_activities);
		
		dbManager = new SQLiteDataManager("MyDB", this);
		updateRunningItems();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		updateRunningItems();
	}
	
	private long[] getIdsForActivities(List<TrackLog> activities) {
		long[] ids = new long[activities.size()];
		for (int i = 0; i < activities.size(); i++) {
			ids[i] = activities.get(i).getActivityId();
		}
		return ids;
	}
	
	private void updateRunningItems() {
		activities = dbManager.getActivities(true);
		long[] ids = getIdsForActivities(activities);
		activitiesMap = dbManager.getActivitiesByIds(ids);
		
		RunningItemAdapter adapter = new RunningItemAdapter(this, R.layout.item_row, activities);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		setListAdapter(adapter);
		
		ListView lv = getListView();
		registerForContextMenu(lv);
		
		lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				showStopTrackingDialog(activitiesMap.get(activities.get(position).getActivityId()));
			}
		});
	}
	
	private void checkAchievements() {
		AchievementsActivity.checkNotCompleted(this);
	}
	
	/**
     * Prompts the user for confirmation of the stop tracking process. 
     */
    private void showStopTrackingDialog(final ActivityItem activity) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("You are going to stop the tracking process for the action: " + activity.getName())
    		.setCancelable(false)
    		.setPositiveButton("Stop Tracking", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					boolean success = dbManager.stopTracking(activity);
					// TODO: call update for current track and not for all
					dbManager.updateTrackRows();
					updateRunningItems();
					checkAchievements();
					PlansNotificationManager.getInstance().setNotification(getApplicationContext());
					if (success) {
						Toast.makeText(getApplicationContext(), "Successfully stopped tracking time for action "
								+ activity.getName(), Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getApplicationContext(), "Failed to stop tracking time for action "
								+ activity.getName(), Toast.LENGTH_SHORT).show();
					}
				}
			}).setNegativeButton("Not right now", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
    	AlertDialog alert = builder.create();
    	alert.setTitle("Are you sure?!?"); 
    	alert.setIcon(R.drawable.stop);
    	alert.show();
    }
	
	private class RunningItemAdapter extends ArrayAdapter<TrackLog> {

		private ArrayList<TrackLog> items;

		public RunningItemAdapter(Context context, int textViewResourceId,
				ArrayList<TrackLog> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.item_row, null);
			}

			TrackLog log = items.get(position);

			if (log != null) {
				ActivityItem item = activitiesMap.get(log.getActivityId());
				TextView tvName = (TextView) v.findViewById(R.id.itemName);
				TextView tvInfo = (TextView) v.findViewById(R.id.itemInfo);
				TextView tvStatus = (TextView) v.findViewById(R.id.itemStatus);
				ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.itemProgressBar);
				progressBar.setVisibility(View.GONE);

				if (tvName != null) {
					tvName.setText(item.getName());
				}
				if (tvInfo != null) {
					tvInfo.setText(item.getCategory());
				}
				if (tvStatus != null) {
					tvStatus.setText("Start date: "
							+ String.valueOf(log.getStartDate().toGMTString()));
				}
			}
			return v;
		}
	}
	
}
